<template>
  <div style="padding: 0 16px">
    <div style="padding: 8px 8px">
      <el-button type="danger" plain @click="onStopAll">停止所有</el-button>
      <el-button type="warning" plain @click="onStartAll">启动所有</el-button>
      <el-button type="success" plain @click="onRefresh">刷新</el-button>
    </div>
    <el-tabs v-model="instance">
      <el-tab-pane
        v-for="item of tabs"
        :key="item.instance"
        :label="item.title"
        :name="item.instance"
      >
        <!-- 取消每次切换刷新 -->
        <!-- <keep-alive></keep-alive> -->
        <task-table
          v-if="instance === item.instance"
          ref="tableRef"
          :instance="item.instance"
        />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
import TaskTable from './table/index.vue'
import { InstanceApi } from '@/api/instance'
import { SupervisordApi } from '@/api/supervisord'

export default {
  components: { TaskTable },
  data() {
    return {
      tabs: [],
      instance: ''
    }
  },
  async mounted() {
    const {
      data: { data }
    } = await InstanceApi.getData()
    this.tabs = data
    this.instance = data[0]?.instance
  },
  methods: {
    onStopAll() {
      this.$confirm('此操作将停止所有进程, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          SupervisordApi.jobAction(this.instance, 'stop').then((resp) => {
            const data = resp.data
            if (data.code === 200) {
              this.$message({
                type: 'success',
                message: '批量停止成功!'
              })
              this.$refs.tableRef[0].fetchData()
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消停止'
          })
        })
    },
    onStartAll() {
      this.$confirm('此操作将启动所有进程, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          SupervisordApi.jobAction(this.instance, 'start').then((resp) => {
            const data = resp.data
            if (data.code === 200) {
              this.$message({
                type: 'success',
                message: '批量启动成功!'
              })
              this.$refs.tableRef[0].fetchData()
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消启动'
          })
        })
    },
    onRefresh() {
      this.$refs.tableRef[0].fetchData()
      this.$message({
        message: '刷新成功！',
        type: 'success'
      })
    }
  }
}
</script>
